#include "user.h"
#include "thread_pool.h"
#include <stdio.h>
#include <string.h>
#include <shadow.h>
#include "virtual_file.h"

//extern file_t* file;

static void get_setting(char *setting,char *passwd)
{
    int i,j;
    //取出salt,i 记录密码字符下标，j记录$出现次数
    for(i = 0,j = 0; passwd[i] && j != 4; ++i) {
        if(passwd[i] == '$')
            ++j;
    }
    strncpy(setting, passwd, i);
}

void loginCheck1(user_info_t * user, int sockfd, char* user_name, SQL_CONN_POOL* sp)
{
    printf("loginCheck1.\n");
    train_t t;
    int ret;
    memset(&t, 0, sizeof(t));

    //mysql中查表
    int user_flag = 0; 
    user_flag = isUser(sp, user_name);
    
    if(user_flag == 1){
        //用户存在，把密文头发给客户端
        printf("用户存在！\n");
        
        //获取salt值
        char setting[512] = {0};
        mysql_select_salt(sp, user_name, setting);
        
        t.len = strlen(setting);
        t.type = TASK_LOGIN_SECTION1_RESP_OK;
        strncpy(t.buff, setting, t.len);

        strcpy(user->encrypted, setting);
        ret = sendn(sockfd, &t, 4 + 4 + t.len);
        printf("ret: %d\n", ret);
    } else {// 用户不存在的情况下
        t.len = 0;   
        t.type = TASK_LOGIN_SECTION1_RESP_ERROR;
        ret = sendn(user->sockfd, &t, 8);
        printf("check1 send %d bytes.\n", ret);
        return;
    }
}

void loginCheck2(user_info_t * user, int sockfd, const char* username, const char* encrypted, SQL_CONN_POOL* sp)
{
    printf("loginCheck2.\n"); 
    int ret;
    train_t t;
    memset(&t, 0, sizeof(t));
    
    //连接数据库查找密文
    char cryptpasswd[128] = {0};
    mysql_select_crypt(sp, username, cryptpasswd);

    if(strcmp(cryptpasswd, encrypted) == 0) {
        //登录成功
        user->status = STATUS_LOGIN;//更新用户登录成功的状态
        t.type = TASK_LOGIN_SECTION2_RESP_OK;

        //获得file信息
        //login_getfile(sp, username, user->file);

        //用户目录
        char dir[128] = {0};
        char pwd[128] = {0};
        int uid;
        int path_id;
        //获取当前目录的id, 和用户id
        mysql_select_pwd(sp, username, &uid, &path_id);

        printf("uid:%d, path_id:%d\n", uid, path_id);
        
        //获取完整路径 
        get_pwd(sp, path_id, uid, pwd);
        sprintf(pwd,"%s$",pwd);
        t.len = strlen(pwd);
        strcpy(t.buff, pwd);
        ret = sendn(sockfd, &t, 8 + t.len);
        printf("Login success.\n");

        //切换目录
        sprintf(dir,"../user");
        ret = chdir(dir);
        char buff[128] = {0};
        getcwd(buff, sizeof(buff));
        puts(buff);

    } else {
        //登录失败, 密码错误
        t.type = TASK_LOGIN_SECTION2_RESP_ERROR;
        printf("Login failed.\n");
        ret = sendn(sockfd, &t, 8);
    }
    printf("check2 send %d bytes.\n", ret);
    return;
}

